package com.niodata.dp.expression.function.string;

import com.googlecode.aviator.runtime.function.AbstractVariadicFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.util.Map;

public class StringFormatFunction extends AbstractVariadicFunction {

  @Override
  public String getName() {
    return "string.format";
  }

  @Override
  public AviatorObject variadicCall(Map<String, Object> env, AviatorObject... aviatorObjects) {
    String fmt = FunctionUtils.getStringValue(aviatorObjects[0], env);
    Object[] values = null;
    if (aviatorObjects.length == 2 && aviatorObjects[1].getValue(env).getClass().isArray()) {
      values = (Object[]) aviatorObjects[1].getValue(env);
    } else {
      int idx = 1;
      values = new Object[aviatorObjects.length - 1];
      for (; idx < aviatorObjects.length; idx++) {
        AviatorObject avo = aviatorObjects[idx];
        values[idx - 1] = avo.getValue(env);
      }
    }
    String result = String.format(fmt, values);
    return FunctionUtils.wrapReturn(result);
  }
}
